//
//  NSDate+Category.m
//  VIVideoPlayer
//
//  Created by lan's Mac on 2022/6/28.
//

#import "NSDate+Category.h"

static const unsigned componentFlags = (NSCalendarUnitYear| NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekOfMonth |  NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitWeekday | NSCalendarUnitWeekdayOrdinal);

@implementation NSDate (Category)

+ (NSString *)getCurrentTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    return dateTime;
}

+ (NSString *)getCurrentTimestamp {
    NSDate *dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval interval=[dat timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%0.f", interval*1000];//转为字符型
    return timeString;
}

+ (NSString *)getTimestampZeroString:(NSString *)str {
    str = [str stringByAppendingString:@" 00:00:00"];
    return [self getTimeStrWithString:str];
}

+ (NSString *)getTimeStrWithString:(NSString *)str{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];// 创建一个时间格式化对象
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; //设定时间的格式
    NSDate *tempDate = [dateFormatter dateFromString:str];//将字符串转换为时间对象
    NSString *timeStr = [NSString stringWithFormat:@"%ld", (long)[tempDate timeIntervalSince1970]*1000];//字符串转成时间戳,精确到毫秒*1000
    return timeStr;
}

+ (NSString *)getTimeStrWithStringYmd:(NSString *)str{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];// 创建一个时间格式化对象
    [dateFormatter setDateFormat:@"YYYY-MM-dd"]; //设定时间的格式
    NSDate *tempDate = [dateFormatter dateFromString:str];//将字符串转换为时间对象
    NSString *timeStr = [NSString stringWithFormat:@"%ld", (long)[tempDate timeIntervalSince1970]*1000];//字符串转成时间戳,精确到毫秒*1000
    return timeStr;
}


#pragma mark 时间戳 转日期 （yyyy-MM-dd）
+ (NSString *)timeWithYearMonthDayCountDown:(NSString *)timestamp {
    return [self timestamp:timestamp.doubleValue dateFormatterString:kDateFormateDay];
}

+ (NSString *)timeWithYearMonthDayHourMinSecCountDown:(NSString *)timestamp {
    return [self timestamp:timestamp.doubleValue dateFormatterString:kDateFormateSecond];
}

+ (NSString *)timeStringWithTimeInterval:(NSInteger)timeInterval {
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval/1000];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"YYYY-MM-dd";
    return [formatter stringFromDate:date];
}

+ (NSString *)timestamp:(NSTimeInterval)timestamp dateFormatterString:(NSString *)dateFormatterString{
    // 传入的时间戳timeStr如果是精确到毫秒的记得要/1000
    NSTimeInterval timeInterval = timestamp/1000;
    NSDate *detailDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    // 实例化一个NSDateFormatter对象，设定时间格式，这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:dateFormatterString];
    NSString *dateStr = [dateFormatter stringFromDate:detailDate];
    return dateStr;
}
+ (NSString *)yearToSecond:(NSTimeInterval)timestamp{
    return [self timestamp:timestamp dateFormatterString:kDateFormateSecond];
}

- (NSDateFormatter *)dateFormatter:(NSString *)formatter {
    NSDateFormatter *fm = [[NSDateFormatter alloc] init];
    [fm setDateFormat:formatter];
    return fm;
}

- (NSString *)dateDay {
    return [[self dateFormatter:kDateFormateDay] stringFromDate:self];
}
- (NSString *)dateDay2 {
    return [[self dateFormatter:kDateFormateDay2] stringFromDate:self];
}
- (NSString *)dateSecond {
    return [[self dateFormatter:kDateFormateSecond] stringFromDate:self];
}

- (NSString *)dateMinute {
    return [[self dateFormatter:kDateFormateMin] stringFromDate:self];
}

//将UTC日期转为本地时间字符串
//输入的UTC日期格式2013-08-03T04:53:51+0000
+ (NSString *)getLocalDateFormateUTCDate:(NSDate *)utcDate {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //输入格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
    NSTimeZone *localTimeZone = [NSTimeZone localTimeZone];
    [dateFormatter setTimeZone:localTimeZone];
    //输出格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString = [dateFormatter stringFromDate:utcDate];
    return dateString;
}

/// 获取最近几天时间数组
/// @param startDate 当前时间
/// @param count 几天
+ (NSMutableArray *)latelyWeekTime:(NSDate *)startDate dayCount:(NSInteger)count {
    NSMutableArray *dateArray = [[NSMutableArray alloc] init];
    for (int i = 0; i < count; i ++) {
        //从现在开始的24小时
        NSTimeInterval secondsPerDay = -i * 24 * 60 * 60;
        NSDate *curDate;
        if (startDate != nil) {
              curDate = [NSDate dateWithTimeInterval:secondsPerDay sinceDate:startDate];
        }else{
              curDate = [NSDate dateWithTimeIntervalSinceNow:secondsPerDay];
        }
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"MM-dd"];
        NSString *dateStr = [dateFormatter stringFromDate:curDate];//几月几号
        [dateArray addObject:dateStr];
    }
    return dateArray;
}

/// 获取今天的日期(格式：MMdd)
+ (NSString *)getTodayStringMMdd {
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"MM-dd"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    return dateTime;
}

/// 获取当前时间的月-日
+ (NSString *)getLocalDateFormateMMdd:(NSDate *)utcDate{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //输入格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
    NSTimeZone *localTimeZone = [NSTimeZone localTimeZone];
    [dateFormatter setTimeZone:localTimeZone];
    //输出格式
    [dateFormatter setDateFormat:@"MM-dd"];
    NSString *dateString = [dateFormatter stringFromDate:utcDate];
    return dateString;
}


+ (NSDate *)replaceDateStrToUTC:(NSDate *)originDate replaceStr:(NSString *)replaceStr {
    NSString *newDateStr = [self replaceDateStr:originDate replaceStr:replaceStr];
    return [self stringToDate:newDateStr format:@"yyyy-MM-dd HH:mm:ss"];
}

+ (NSString *)replaceDateStr:(NSDate *)originDate replaceStr:(NSString *)replaceStr {
    //截取的时间日期
    NSString *originStr = [self dateToString:originDate format:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString *bStr = [originStr substringWithRange:NSMakeRange(5,5)];
    
    NSString *newDateStr = [originStr stringByReplacingOccurrencesOfString:bStr withString:replaceStr];
    return newDateStr;
}

+ (NSDate *)stringToDate:(NSString *)datestr format:(NSString *)format {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:[NSLocale currentLocale]];
    [dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
    [dateFormatter setDateFormat:format];
    NSDate *date = [dateFormatter dateFromString:datestr];
#if ! __has_feature(objc_arc)
    [dateFormatter release];
#endif
    return date;
}

+ (NSString *)dateToString:(NSDate *)date format:(nonnull NSString *)format {
    if(!format){
        format = @"yyyy-MM-dd HH:mm:ss";
    }
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format];
    
    NSString *dateStr = [dateFormatter stringFromDate: date];
    return dateStr;
}

/// 获取当前的日历
+ (NSCalendar *)currentCalendar {
    static NSCalendar *sharedCalendar = nil;
    if (!sharedCalendar)
        sharedCalendar = [NSCalendar autoupdatingCurrentCalendar];
    return sharedCalendar;
}

- (NSDateComponents *)getComponents {
    NSDateComponents *components = [[NSDate currentCalendar] components:componentFlags fromDate:self];
    return components;
}

- (NSDate *)dateWithFormatter:(NSString *)formatter {
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = formatter;
    NSString *selfStr = [fmt stringFromDate:self];
    return [fmt dateFromString:selfStr];
}

/// 比较两个日期的大小
+ (BOOL)compareDate:(NSDate*)start withDate:(NSDate*)end {
    NSComparisonResult result = [start compare: end];
    if (result == NSOrderedAscending || result == NSOrderedSame) {
        //结束时间大于、等于开始时间
        return YES;
    }else if (result==NSOrderedDescending) {
        //结束时间小于开始时间
        return NO;
    }
    return NO;
}

+ (NSInteger)compareDeviationDate:(NSString *)start withDate:(NSString *)end {
    NSString *startStr = [self timeWithYearMonthDayCountDown:start];
    NSString *endStr = [self timeWithYearMonthDayCountDown:end];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *startDate = [dateFormatter dateFromString:startStr];
    NSDate *endDate = [dateFormatter dateFromString:endStr];
    //利用NSCalendar比较日期的差异
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSCalendarUnit unit = NSCalendarUnitDay;//只比较天数差异
    //比较的结果是NSDateComponents类对象
    NSDateComponents *delta = [calendar components:unit fromDate:startDate toDate:endDate options:0];
    //获取其中的"天"
    return delta.day;
}

/// 是否是七天内
+ (BOOL)isWithinSevendays:(NSDate *)date {
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSDate *nowDate = [fmt dateFromString:[fmt stringFromDate:[NSDate date]]];
    NSDate *selfDate = [fmt dateFromString:[fmt stringFromDate:date]];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *cmps = [calendar components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:selfDate toDate:nowDate options:0];
   return cmps.year == 0 && cmps.month == 0 && cmps.day < 7;
}

/// 获取当前对象日期前后多少天的日期
/// @param dDays 前后多少天 (30:表示30天后  -30：表示30天前)
- (NSDate *)dateByAddingDays:(NSInteger)dDays {
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    [dateComponents setDay:dDays];
    NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:self options:0];
    return newDate;
}

- (NSDate *)cxy_dateByAddingDays:(NSInteger)dDays {
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    [dateComponents setDay:dDays+1];
    NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:self options:0];
    NSArray *array = [newDate.dateSecond componentsSeparatedByString:@" "];
    if (array.count == 2) {
        NSString *timeStr = array.firstObject;
        timeStr = [timeStr stringByAppendingString:@" 00:00:00"];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        return [dateFormatter dateFromString:timeStr];
    }
    return newDate;
}

- (NSString *)datePrefix3Day {
    NSDate *date = [self dateByAddingDays:-2];
    return date.dateDay;
}

- (NSString *)datePrefix7Day {
    NSDate *date = [self dateByAddingDays:-6];
    return date.dateDay;
}

/// 检查选择的日期时间是否超过当前时间
/// @param startDate 选择的时间
+ (BOOL)checkCurrentDateEarlierThanStartDate:(NSDate *)startDate {
    NSDate *currentDate = [NSDate date];
    return ([currentDate compare:startDate] == NSOrderedAscending);
}

+ (BOOL)judgeTimeByStartAndEnd:(NSDate *)startDate EndTime:(NSDate *)endDate currentDate:(NSDate *)currentDate {
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    // 时间格式,建议大写    HH 使用 24 小时制；hh 12小时制
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString * currentDateStr = [dateFormat stringFromDate:currentDate];//将日期转换成字符串
    NSString *startStr = [dateFormat stringFromDate:startDate];
    NSString *endStr = [dateFormat stringFromDate:endDate];
    currentDate = [dateFormat dateFromString:currentDateStr];//转换成NSDate类型。日期置为方法默认日期
    //start end 格式 "2016-05-18 9:00:00"
    NSDate *start = [dateFormat dateFromString:startStr];
    NSDate *expire = [dateFormat dateFromString:endStr];
    if ([currentDate compare:start] == NSOrderedDescending && [currentDate compare:expire] == NSOrderedAscending) {
        return YES;
    }
    return NO;
}

- (NSString *)stringWithFormat:(NSString *)format {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:format];
    [formatter setLocale:[NSLocale currentLocale]];
    return [formatter stringFromDate:self];
}

- (NSDate *)dateByAddingYears:(NSInteger)years {
    NSCalendar *calendar =  [NSCalendar currentCalendar];
    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setYear:years];
    return [calendar dateByAddingComponents:components toDate:self options:0];
}

+ (NSString *)dayBeginSecondString{
    return [NSString stringWithFormat:@"%@ 00:00:00",NSDate.date.dateDay];
}
+ (NSTimeInterval)dayBegin{
    NSString *todayStr = [self dayBeginSecondString];
    NSDate *date = [NSDate stringToDate:todayStr format:kDateFormateSecond];
    return [date timeIntervalSince1970]*1000;
}

+ (NSString *)dayEndSecondString{
    return [NSString stringWithFormat:@"%@ 23:59:59",NSDate.date.dateDay];
}

+ (NSTimeInterval)dayEnd{
    NSString *todayStr = [self dayEndSecondString];
    NSDate *date = [NSDate stringToDate:todayStr format:kDateFormateSecond];
    return [date timeIntervalSince1970]*1000;
}
+ (NSTimeInterval)dayNow{
    NSDate *date = [NSDate stringToDate:NSDate.date.dateSecond format:kDateFormateSecond];
    return [date timeIntervalSince1970]*1000;
}
+ (NSTimeInterval)dayBefore3Day{
    NSDate *date1 = [NSDate.date dateByAddingDays:-2];
    NSString *str = [date1.dateDay stringByAppendingString:@" 00:00:00"];
    NSDate *date2 = [NSDate stringToDate:str format:kDateFormateSecond];
    return [date2 timeIntervalSince1970]*1000;
}
+ (NSTimeInterval)dayBefore7Day{
    NSDate *date1 = [NSDate.date dateByAddingDays:-6];
    NSString *str = [date1.dateDay stringByAppendingString:@" 00:00:00"];
    NSDate *date2 = [NSDate stringToDate:str format:kDateFormateSecond];
    return [date2 timeIntervalSince1970]*1000;
}

+ (NSTimeInterval)dayBeforeNDay:(NSInteger)nDay {
    NSDate *date1 = [NSDate.date dateByAddingDays:-nDay+1];
    NSString *str = [date1.dateDay stringByAppendingString:@" 00:00:00"];
    NSDate *date2 = [NSDate stringToDate:str format:kDateFormateSecond];
    return [date2 timeIntervalSince1970]*1000;
}

+ (NSString *)monthBeginSecondString{
    NSString *month = [[NSDate.date dateFormatter:kDateFormateMonth] stringFromDate:NSDate.date];
    return [NSString stringWithFormat:@"%@-01 00:00:00",month];
}

+ (NSTimeInterval)monthBegin{
    NSString *todayStr = [self monthBeginSecondString];
    NSDate *date = [NSDate stringToDate:todayStr format:kDateFormateSecond];
    return [date timeIntervalSince1970]*1000;
}
+ (NSTimeInterval)lastMonthBegin{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *cmp = [calendar components:(NSCalendarUnitMonth|NSCalendarUnitYear) fromDate:NSDate.date];
    [cmp setMonth:cmp.month-1];
    NSDate *date = [calendar dateFromComponents:cmp];
    return [date timeIntervalSince1970]*1000;
}
+ (NSTimeInterval)lastMonthEnd{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate * firstDate = nil;
    double interval = 0;
    NSDate * lastDate = nil;
    
    NSDateComponents *cmp = [calendar components:(NSCalendarUnitMonth|NSCalendarUnitYear) fromDate:NSDate.date];
    [cmp setMonth:cmp.month-1];
    NSDate *date = [calendar dateFromComponents:cmp];
    
    BOOL ok = [calendar rangeOfUnit:NSCalendarUnitMonth startDate:&firstDate interval:&interval forDate:date];
    if(ok){
        lastDate = [firstDate dateByAddingTimeInterval:interval-1];
    }
    return [lastDate timeIntervalSince1970]*1000;
}


@end
